import {login,createPay,getMerchantDiscountInfo} from '../../../Tools/HTTPOpertion.js';
Page({
  data: {
    obj: {},
    info: {},
    money: 0,
    resultMoney:0,
    ratio: 0.00,
    resultRatio:"0.00",
    merchantId:'',
    panduanMon:'',
    qingkong:'',
    bul:true,
    isFocus:false
  },
  onLoad: function (options) {
    const url1= decodeURIComponent(options.q),id = url1.split("=")[1],token=wx.getStorageSync('token');
    this.data.merchantId=id;
    if(!id){
        wx.showToast({
          title:'网络错误，请稍后再试',
          icon:'none'
        })
        return false;
    }
    if(token){
      this.setData({isFocus:true})
      this.loadInfo(id)
    }else{
      this.getData()
    }
  },
  getData:function(){
    const that=this;
    wx.showLoading({title:'登录中'})
    login('notoken','flag').then(res=>{
      wx.hideLoading()
      res.token && wx.setStorageSync('token', res.token);
      that.setData({isFocus:true})
      const id=that.data.merchantId;
      if (id) {
        that.loadInfo(id);
      }else{
        wx.showToast({
          title:'网络错误，请稍后再试',
          icon:'none'
        })
      }
    })
    .catch(err=>{
      wx.showToast({
        title:'网络错误，请稍后再试',
        icon:'none'
      })
    })
  },
// 跳转主页
  goBackHome: function() {
    wx.reLaunch({
      url: '/pages/spellGroupHome/spellGroupHome'
    });
  },
  // 优惠活动与实付金额
  inputMoney: function (e) {
    if(this.data.bul){return false;}
    const moneyNum=e.detail.value;
    if (e.detail.value==''){
      this.setData({
        resultRatio: 0
      })
    }
    this.setData({
      panduanMon: e.detail.value
    })
    if (e.detail.value <= 100000.00 && e.detail.value>=0.01) {
      this.setData({
        resultRatio: "0.00",
        money: e.detail.value
      });
      var self = this;
      // 打折
      if (this.data.info.discountMode == "MR") {
        var dz = e.detail.value * parseFloat(this.data.info.rebate) / 10 + '';
        console.log(dz)
        var qud;
        if (dz.indexOf('.')>0&&dz.split('.')[1].charAt(2) == 0) {
          qud = Math.floor(dz * 100) / 100;
        } else {
          qud = dz;
        }
        this.setData({
          money:e.detail.value,
          resultMoney: this.data.info.rebate == 0 ? e.detail.value :qud
        });
      }

      // 满减
      if (this.data.info.discountMode == "MD") {
        var self = this;
        var result = e.detail.value;
        console.log(result)
        self.setData({
          money: e.detail.value,
          resultMoney: result
        });
        this.data.info.mInfo&&this.data.info.mInfo.forEach(function (item) {

          if (parseFloat(e.detail.value) >= parseFloat(item.full / 100)) {

            result = result > e.detail.value-item.subtract / 100 || result == 0 ? e.detail.value-item.subtract / 100 : result;
            result=parseFloat(result).toFixed(3);
            console.log(result)
            self.setData({
              money: e.detail.value,
              resultMoney: result
            });
            console.log(result)
          }
        });
      }
      // 如果没有满减或打折
      if (this.data.info.discountMode == 'undefined' || this.data.info.discountMode == 'null' || !this.data.info.discountMode) {
        this.setData({
          money: e.detail.value,
          resultMoney: e.detail.value //减去 减满
        });
      }

      // 实付金额
      var resultM = this.data.resultMoney == 0 ? "" : this.data.resultMoney;

      resultM = Math.ceil(resultM * 1000) / 1000;
      resultM = Math.ceil(Math.ceil(resultM * 1000) / 10) / 100;
      // ~~：转换为数字（实付金额后面加小数点）
      resultM = ~~resultM / 100 == resultM / 100 ? resultM  + ".00" : resultM;
      // console.log((resultM * 100))
      var resultMStr = resultM + "";
      // console.log(resultMStr)
      if (resultMStr.split(".").length > 1) {
        if (resultMStr.split(".")[1].length < 2) {
          resultMStr = resultM + "0";
        }
      }
      this.setData({
        resultMoney:resultMStr
      });

      let resultRatio = parseFloat(resultMStr) * this.data.ratio / 100;
      if (resultRatio < 0.01) {
        this.setData({
          resultRatio: 0.01,
        });
      } else {
        resultRatio =resultRatio.toFixed(2)
        this.setData({
          resultRatio: resultRatio,
        });
      }

    }else{
      if (e.detail.value<0.01){
          this.setData({
            resultMoney:"0.00"
          })
      }
      if (e.detail.value>100000.00){
          wx.showToast({
            title: "单笔金额最大为十万元，请重新输入",
            icon: 'none',
            duration: 1000
          })
          return;
      }

    }

  },
  // 确认买单
  qrmdTap: function () {
    if(this.data.bul){
      wx.showToast({
        title:'获取商户信息失败，请稍后再试',
        icon:'none',
        duration:2000
      })
      return false;
    }
    var self = this;
// 验证金额
    if (self.data.resultMoney <=0) {
        wx.showToast({
          title: "请输入金额",
          icon: 'none',
          duration: 2000
        })
        return false;
      }
//  验证小数
    var re = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    if (!re.test(self.data.money)) {
      wx.showToast({
        title: "只支持输入小数点后两位，请重新输入",
        icon: 'none',
        duration: 2000
      })
      return false;
    }
// 验证最大额度
    if (self.data.panduanMon > 100000.00) {
      wx.showToast({
        title: "单笔金额最大为十万元，请重新输入",
        icon: 'none',
        duration: 1000
      })
      return false;
    }
    var strnum=Math.round(self.data.resultMoney*100)+"";
    var strmon = Math.round(self.data.money * 100) + ""
    var config = { merchantName: self.data.info.name, money: strnum, origionPrice: strmon, merchantId: self.data.info.id, ratio: self.data.info.ratio ? self.data.info.ratio : "0" };
    createPay(config).then(function (result) {
      wx.requestPayment({
        'timeStamp': result.timeStamp,
        'nonceStr': result.nonceStr,
        'package': result.package,
        'signType': 'MD5',
        'paySign': result.paySign,
        'success': function (res) {
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 2000
          })
          wx.reLaunch({
            url: '/pages/PaymentSuccess/PaymentSuccess?tradeId=' + result.tradeId,
          })
        },
        'fail': function (res) {
          console.log(res);
          wx.showToast({
            title: '支付失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }).catch(function (error) {
      wx.showToast({
        title: error.message||'网络错误，请稍后再试',
        icon: 'none',
        duration: 2000
      })
    });

  },
  // 通过商户id获取商户信息：id为商户id
  loadInfo: function (id) {
    var self = this;
    getMerchantDiscountInfo({ cnd: id }).then(function (result) {
      if (result.code==0){
          self.setData({
            bul: false,
            info: result.data,
            ratio: parseFloat(result.data.ratio)
          })

      } else{
        self.setData({
          bul: true
        })
        wx.showToast({
          title: result.message || '网络错误，请稍后再试',
          icon: 'none',
          duration: 2000
        });
      }
    }).catch(function (error) {
      wx.showToast({
        title:'网络错误，请稍后再试',
        icon: 'none',
        duration: 2000
      });
    });
  },
  setuserinfo:function(){
    this.getData()
  }
})
